#include "stdafx.h"
#include "MultiByteTransfer.h"

namespace COMMONLIB
{
	CharToWChar::CharToWChar(const char* pValue, UINT uCodePage /*= CP_ACP*/):m_pBuff(NULL)
	{
		Convert(pValue, uCodePage);
	}

	CharToWChar::CharToWChar():m_pBuff(NULL)
	{

	}

	CharToWChar::~CharToWChar()
	{
		std::vector<WCHAR*>::iterator it = m_vectBuff.begin();
		for (; it != m_vectBuff.end(); it++)
		{
			WCHAR* p = *it;
			if (p != NULL)
			{
				delete[] p;
			}
		}

		m_vectBuff.clear();
	}

	void CharToWChar::ResetValue(const char* pValue, UINT uCodePage/* = CP_ACP*/)
	{
		m_pBuff = NULL;
		Convert(pValue, uCodePage);
	}

	const WCHAR* CharToWChar::GetP()
	{
		return m_pBuff;
	}


	void CharToWChar::Convert(const char* pValue, UINT uCodePage)
	{
		if (pValue != NULL)
		{
			int nLen = strlen(pValue);
			if (nLen > 0)
			{
				int nNeed = MultiByteToWideChar(uCodePage, NULL, pValue, nLen, NULL, NULL);
				if (nNeed != 0)
				{
					m_pBuff = new WCHAR[nNeed+1];
					if (m_pBuff != NULL)
					{
						m_vectBuff.push_back(m_pBuff);
						ZeroMemory(m_pBuff, nNeed+1);
						MultiByteToWideChar(uCodePage, NULL, pValue, nLen, m_pBuff, nNeed);
						m_pBuff[nNeed] = L'\0';
					}
				}
			}
			else
			{
				m_pBuff = new WCHAR[1];
				if (m_pBuff != NULL)
				{
					m_vectBuff.push_back(m_pBuff);
					*m_pBuff = L'\0';
				}
			}
		}
	}

//////////////////////////////////////////////////////////////////////////

	WCharToChar::WCharToChar(const WCHAR* pValue, UINT uCodePage /*= CP_ACP*/):m_pBuff(NULL)
	{
		Convert(pValue, uCodePage);
	}

	WCharToChar::WCharToChar():m_pBuff(NULL)
	{

	}

	WCharToChar::~WCharToChar()
	{
		std::vector<char*>::iterator it = m_vectBuff.begin();
		for (; it != m_vectBuff.end(); it++)
		{
			char* p = *it;
			if (p != NULL)
			{
				delete[] p;
			}
		}

		m_vectBuff.clear();
	}

	const char* WCharToChar::GetP()
	{
		return m_pBuff;
	}

	void WCharToChar::ResetValue(const WCHAR* pValue, UINT uCodePage /*= CP_ACP*/)
	{
		m_pBuff = NULL;
		Convert(pValue, uCodePage);
	}

	void WCharToChar::Convert(const WCHAR* pValue, UINT uCodePage)
	{
		if (pValue != NULL)
		{
			int nLen = wcslen(pValue);
			if (nLen > 0)
			{
				int nNeed = WideCharToMultiByte(uCodePage, NULL, pValue, nLen, NULL, NULL, NULL, NULL);
				if (nNeed != 0)
				{
					m_pBuff = new char[nNeed+1];
					if (m_pBuff != NULL)
					{
						m_vectBuff.push_back(m_pBuff);
						ZeroMemory(m_pBuff, nNeed+1);
						WideCharToMultiByte(uCodePage, NULL, pValue, nLen, m_pBuff, nNeed, NULL, NULL);
						m_pBuff[nNeed] = '\0';
					}
				}
			}
			else
			{
				m_pBuff = new char[1];
				if (m_pBuff != NULL)
				{
					m_vectBuff.push_back(m_pBuff);
					*m_pBuff = '\0';
				}				
			}
		}
	}
}